﻿using System;
using System.Collections.Generic;
using System.Data;

//using System.Data.DataSetExtensions;
using System.Linq;
using System.Text;

namespace BLL
{
    public class Daxie
    {
        public string Yuan = "元";                         // “元”，可以改为“圆”、“卢布”之类

        public string Jiao = "角";                         // “角”，可以改为“拾”

        public string Fen = "分";                         // “分”，可以改为“美分”之类

        private static string Digit = "零壹贰叁肆伍陆柒捌玖";       // 大写数字
        private bool isAllZero = true;                         // 片段内是否全零

        private bool isPreZero = true;                         // 低一位数字是否是零

        private bool Overflow = false;                        // 溢出标志
        private long money100;                                    // 金额*100，即以“分”为单位的金额

        private long value;                                       // money100的绝对值

        private StringBuilder sb = new StringBuilder();          // 大写金额字符串，逆序

        // 只读属性: "零元"
        public string ZeroString
        {
            get { return Digit[0] + Yuan; }
        }

        // 构造函数

        public Daxie(decimal money)
        {
            try { money100 = (long)(money * 100m); }
            catch { Overflow = true; }
            if (money100 == long.MinValue) Overflow = true;
        }

        // 重载 ToString() 方法，返回大写金额字符串
        public override string ToString()
        {
            if (Overflow) return "金额超出范围";
            if (money100 == 0) return ZeroString;
            string[] Unit = { Yuan, "万", "亿", "万", "亿亿" };
            value = System.Math.Abs(money100);
            ParseSection(true);
            for (int i = 0; i < Unit.Length && value > 0; i++)
            {
                if (isPreZero && !isAllZero) sb.Append(Digit[0]);
                if (i == 4 && sb.ToString().EndsWith(Unit[2]))
                    sb.Remove(sb.Length - Unit[2].Length, Unit[2].Length);
                sb.Append(Unit[i]);
                ParseSection(false);
                if ((i % 2) == 1 && isAllZero)
                    sb.Remove(sb.Length - Unit[i].Length, Unit[i].Length);
            }
            if (money100 < 0) sb.Append("");
            return Reverse();
        }

        // 解析“片段”: “角分(2位)”或“万以内的一段(4位)”

        private void ParseSection(bool isJiaoFen)
        {
            string[] Unit = isJiaoFen ?
             new string[] { Fen, Jiao } :
             new string[] { "", "拾", "佰", "仟" };
            isAllZero = true;
            for (int i = 0; i < Unit.Length && value > 0; i++)
            {
                int d = (int)(value % 10);
                if (d != 0)
                {
                    if (isPreZero && !isAllZero) sb.Append(Digit[0]);
                    sb.AppendFormat("{0}{1}", Unit[i], Digit[d]);
                    isAllZero = false;
                }
                isPreZero = (d == 0);
                value /= 10;
            }
        }

        // 反转字符串

        private string Reverse()
        {
            StringBuilder sbReversed = new StringBuilder();
            for (int i = sb.Length - 1; i >= 0; i--)
                sbReversed.Append(sb[i]);
            string temp = sbReversed.ToString();
            int templast = temp.IndexOf("元");
            if (templast == temp.Length - 1)
            {
                temp += "整";
            }
            return temp;
        }
    }

    public class Gj
    {
        public DataTable SelectHj(DataTable dd, string lie)
        {
            string[] str = lie.Split(',');
            DataTable dt = new DataTable();

            return pagerdatabind(dd, lie);
        }

        /// <summary>
        /// 获取DATAROW的OBJECT数组，用于交换DATATABLE保存
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="colscount"></param>
        /// <returns></returns>
        private object[] getparamsObj(DataRow dr, int colscount)
        {
            object[] param = new object[colscount];
            for (int i = 0; i < colscount; i++)
            {
                if (dr[i].GetType().ToString().Equals("System.Decimal"))
                {
                    decimal tempval = 0;
                    try
                    {
                        tempval = Convert.ToDecimal(dr[i].ToString());
                    }
                    catch
                    {
                        tempval = 0;
                    }
                    param[i] = tempval;
                }
                else if (dr[i].GetType().ToString().Equals("System.DateTime"))
                {
                    DateTime tempval = DateTime.MinValue;
                    try
                    {
                        tempval = DateTime.Parse(dr[i].ToString());
                    }
                    catch
                    {
                        tempval = DateTime.MinValue;
                    }
                    param[i] = tempval;
                }
                else if (dr[i].GetType().ToString().Equals("System.DBNull"))
                {
                    param[i] = System.DBNull.Value;
                }
                else
                {
                    param[i] = dr[i].ToString();
                }
            }
            return param;
        }

        public DataTable pagerdatabind(DataTable CurDataSourse, string lie)
        {
            SplitCol = lie;

            #region 常规查询

            bool iscontinue = true;

            DataTable dt = null;

            if (CurDataSourse != null && CurDataSourse.Rows.Count > 0)
            {
                dt = CurDataSourse.Clone();

                if (iscontinue)
                {
                    List<DataRow> rowlist = new List<DataRow>();
                    foreach (DataRow dr in CurDataSourse.Rows)
                    {
                        for (int i = 0; i < CurDataSourse.Columns.Count; i++)
                        {
                            if (dr[CurDataSourse.Columns[i].ColumnName].ToString().IndexOf("小计") >= 0)
                            {
                                rowlist.Add(dr);
                            }
                            if (dr[CurDataSourse.Columns[i].ColumnName].ToString().IndexOf("合计") >= 0)
                            {
                                rowlist.Add(dr);
                            }
                            if (dr[CurDataSourse.Columns[i].ColumnName].ToString().IndexOf("总计") >= 0)
                            {
                                rowlist.Add(dr);
                            }
                        }
                    }
                    for (int i = 0; i < rowlist.Count; i++)
                    {
                        CurDataSourse.Rows.Remove(rowlist[i]);
                    }

                    rowlist.Clear();
                    for (int i = 0; i < CurDataSourse.Rows.Count; i++)
                    {
                        if (i >= CurDataSourse.Rows.Count) { break; }
                        dt.Rows.Add(getparamsObj(CurDataSourse.Rows[i], CurDataSourse.Columns.Count));
                    }
                    //for (int i = 0; i < CurDataSourse.Rows.Count; i++)
                    //{
                    //    dt.Rows.Add(getparamsObj(CurDataSourse.Rows[i], CurDataSourse.Columns.Count));
                    //}

                    DataTable tempdt = new DataTable();
                    tempdt = dt;

                    try
                    {
                        if (SplitCol != null && SplitCol != "")
                        {
                            if (tempdt != null && tempdt.Rows.Count > 0)
                            {
                                DataRow dr = tempdt.NewRow();

                                dr[SplitCol.Split(',')[0]] = "总计";

                                foreach (var item in SplitCol.Split(',')[1].Split('&'))
                                {
                                    if (tempdt.Columns.Contains(item))
                                    {
                                        dr[item] = tempdt.AsEnumerable().Where(s => s[SplitCol.Split(',')[0]].ToString().Contains("合计") == false && s[item] != null && s[item].ToString() != "").Sum(s => Convert.ToDecimal(s.Field<object>(item).ToString())).ToString();
                                    }
                                }

                                tempdt.Rows.Add(dr);
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                    tempdt = SumColFun(tempdt, SumCol);

                    CurSplitDt = tempdt;
                }
            }
            else
            {
                dt = new DataTable();
            }

            #endregion 常规查询

            return dt;
        }

        /// <summary>
        /// 界面元素值绑定

        /// </summary>
        public void WindowValueBind()
        {
            //lbltotcount.Text = TotRowcount.ToString();
            //lbltotpage.Text = TotPageCount.ToString();
            //lblcurpage.Text = CurPage.ToString();
        }

        #region 小计方法

        public static DataTable SumColFun(DataTable tempdt, string SumCol)
        {
            try
            {
                if (SumCol != null && SumCol != "")
                {
                    if (tempdt != null && tempdt.Rows.Count > 0)
                    {
                        List<object> listUser = tempdt.AsEnumerable().Where(s => s.Field<string>(SumCol.Split(',')[0]).Contains("合计") == false && s.Field<string>(SumCol.Split(',')[0]) != "" && s.Field<string>(SumCol.Split(',')[0]) != null && s.Field<string>(SumCol.Split(',')[0]).Contains("小计") == false && s.Field<string>(SumCol.Split(',')[0]).Contains("总计") == false).GroupBy(s => s.Field<object>(SumCol.Split(',')[0])).Select(s => s.Key).ToList();
                        int index = 0;

                        foreach (var itemCol in listUser)
                        {
                            DataRow dr = tempdt.NewRow();

                            dr[SumCol.Split(',')[0]] = itemCol + "小计";

                            index += tempdt.AsEnumerable().Where(s => s[SumCol.Split(',')[0]].ToString() == itemCol.ToString()).Count();

                            foreach (var item in SumCol.Split(',')[1].Split('&'))
                            {
                                if (tempdt.Columns.Contains(item))
                                {
                                    dr[item] = tempdt.AsEnumerable().Where(s => s[SumCol.Split(',')[0]].ToString() == itemCol.ToString() && s[item] != null && s[item].ToString() != "" && s[item].ToString().Contains("小计") == false && s[item].ToString().Contains("总计") == false && s[item].ToString().Contains("合计") == false).Sum(s => Convert.ToDecimal(s.Field<object>(item).ToString())).ToString();
                                }
                            }
                            tempdt.Rows.InsertAt(dr, index);
                            index++;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return tempdt;
        }

        #endregion 小计方法

        /// <summary>
        /// 小计、合计、统计

        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public DataTable getDtbySum(DataTable dt)
        {
            try
            {
                Colslilst = Colsliststr.Split('@');

                string[] setting = Sumsetting.Split(',');
                string minsumcol = setting[0];//小计列

                string cnmin = "";
                string tminsumcol = setting[1];//合计列

                string cntmin = "";
                string[] bysumcol = setting[2].Split('&');//求和列

                int addedcount = 0;
                Dictionary<string, string> dicbysumcol = new Dictionary<string, string>();
                Dictionary<int, string> vallist = new Dictionary<int, string>();
                Dictionary<string, decimal> val = new Dictionary<string, decimal>();
                Dictionary<DataRow, int> addrowlist = new Dictionary<DataRow, int>();
                decimal[] valarry = new decimal[bysumcol.Length];
                for (int i = 0; i < Colslilst.Length; i++)
                {
                    if (Colslilst[i].Split('&')[1].Equals(minsumcol))//小计列
                    {
                        cnmin = Colslilst[i].Split('&')[0];
                    }
                    if (Colslilst[i].Split('&')[1].Equals(tminsumcol))//合计列
                    {
                        cntmin = Colslilst[i].Split('&')[0];
                    }
                    for (int j = 0; j < bysumcol.Length; j++)//求和列
                    {
                        if (Colslilst[i].Split('&')[1].Equals(bysumcol[j]))
                        {
                            dicbysumcol.Add(bysumcol[j], Colslilst[i].Split('&')[0]);
                        }
                    }
                }
                string oldcols = "";
                int cnminindex = 0;
                int cntminindex = 0;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName.Equals(cnmin))
                    {
                        cnminindex = i;
                    }
                    if (dt.Columns[i].ColumnName.Equals(cntmin))
                    {
                        cntminindex = i;
                    }
                }
                //求和列列对应单元格坐标 KEY:INDEX VALUE：COLNAME
                vallist.Clear();
                foreach (KeyValuePair<string, string> kv in dicbysumcol)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        if (kv.Value.Equals(dt.Columns[i].ColumnName.ToString()))
                        {
                            vallist.Add(i, kv.Value);
                        }
                    }
                }

                #region 小计列

                int rowindex = 0;//游标 行数
                foreach (DataRow dr in dt.Rows)
                {
                    string curcols = dr[cnmin].ToString();

                    if (oldcols.Length <= 0)
                    {
                        oldcols = curcols;
                    }
                    if (curcols.Equals(oldcols))
                    {
                    }
                    else
                    {
                        DataRow adr = dt.NewRow();
                        object[] param = new object[dt.Columns.Count];
                        for (int i = 0; i < param.Length; i++)
                        {
                            if (vallist.ContainsKey(i))
                            {
                                param[i] = val[vallist[i]];
                            }
                            else if (i == cnminindex)
                            {
                                param[i] = oldcols + "小计：";
                            }
                            else
                            {
                                try
                                {
                                    param[i] = DBNull.Value;
                                }
                                catch
                                {
                                    param[i] = 0;
                                }
                            }
                        }
                        adr.ItemArray = param;
                        addrowlist.Add(adr, rowindex + addedcount);
                        addedcount++;
                        valarry = new decimal[bysumcol.Length];
                        oldcols = curcols;
                    }
                    rowindex++;
                    int arryindex = 0;
                    val.Clear();
                    foreach (KeyValuePair<string, string> kv in dicbysumcol)
                    {
                        decimal inttemp = 0;
                        try
                        {
                            inttemp = Convert.ToDecimal(dr[kv.Value].ToString());//decimal.Parse(dr[kv.Value].ToString());
                        }
                        catch
                        {
                            inttemp = 0;
                        }
                        valarry[arryindex] += inttemp;//求和
                        val.Add(kv.Value, valarry[arryindex]);
                        arryindex++;
                    }
                }
                foreach (KeyValuePair<DataRow, int> kv in addrowlist)
                {
                    dt.Rows.InsertAt(kv.Key, kv.Value);
                }
                DataRow adrlast = dt.NewRow();
                object[] paramlast = new object[dt.Columns.Count];
                for (int i = 0; i < paramlast.Length; i++)
                {
                    if (vallist.ContainsKey(i))
                    {
                        try
                        {
                            paramlast[i] = val[vallist[i]];
                        }
                        catch
                        {
                            paramlast[i] = System.DBNull.Value;
                        }
                    }
                    else if (i == cnminindex)
                    {
                        paramlast[i] = oldcols + "小计：";
                    }
                    else
                    {
                        try
                        {
                            paramlast[i] = DBNull.Value;
                        }
                        catch
                        {
                            paramlast[i] = 0;
                        }
                    }
                }
                adrlast.ItemArray = paramlast;
                dt.Rows.Add(adrlast);

                #endregion 小计列

                #region 合计列 对小计列进行合计

                rowindex = 0;
                oldcols = "";
                addedcount = 0;
                string curcolstmin = "";
                addrowlist.Clear();
                valarry = new decimal[bysumcol.Length];
                val.Clear();
                object[] totparam = new object[dt.Columns.Count];
                totparam[0] = "总计：";
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr[cnmin].ToString().IndexOf("小计") >= 0)//判断是否为小计列
                    {
                        //对小计列求和
                        int arryindex = 0;
                        val.Clear();
                        foreach (KeyValuePair<string, string> kv in dicbysumcol)
                        {
                            decimal inttemp = 0;
                            try
                            {
                                inttemp = Convert.ToDecimal(dr[kv.Value].ToString());//decimal.Parse(dr[kv.Value].ToString());
                            }
                            catch
                            {
                                inttemp = 0;
                            }
                            valarry[arryindex] += inttemp;//求和
                            val.Add(kv.Value, valarry[arryindex]);
                            arryindex++;
                        }
                    }
                    if ((dr[cnmin].ToString().IndexOf("小计") < 0))//过滤小计列 求和值不为空的时候
                    {
                        if (!tminsumcol.Equals("null"))
                        {
                            curcolstmin = dr[cntmin].ToString();
                        }
                        else
                        {
                            curcolstmin = dr[cnmin].ToString();
                        }
                        if (oldcols.Length <= 0)
                        {
                            oldcols = curcolstmin;
                        }
                        if (!curcolstmin.Equals(oldcols))
                        {
                            DataRow adr = dt.NewRow();
                            object[] param = new object[dt.Columns.Count];
                            for (int i = 0; i < param.Length; i++)
                            {
                                if (vallist.ContainsKey(i))
                                {
                                    param[i] = val[vallist[i]];
                                    totparam[i] = val[vallist[i]] + (totparam[i] == null ? 0 : Convert.ToDecimal(totparam[i].ToString()));//decimal.Parse(totparam[i].ToString()));
                                }
                                else if (i == cntminindex)
                                {
                                    param[i] = oldcols + "合计：";
                                }
                                else
                                {
                                    try
                                    {
                                        param[i] = DBNull.Value;
                                    }
                                    catch
                                    {
                                        param[i] = 0;
                                    }
                                }
                            }
                            if (!tminsumcol.Equals("null"))
                            {
                                adr.ItemArray = param;
                                addrowlist.Add(adr, rowindex + addedcount);
                                addedcount++;
                            }
                            valarry = new decimal[bysumcol.Length];
                            oldcols = curcolstmin;
                        }
                    }

                    rowindex++;
                }
                foreach (KeyValuePair<DataRow, int> kv in addrowlist)
                {
                    dt.Rows.InsertAt(kv.Key, kv.Value);
                }
                adrlast = dt.NewRow();
                paramlast = new object[dt.Columns.Count];
                for (int i = 0; i < paramlast.Length; i++)
                {
                    if (vallist.ContainsKey(i))
                    {
                        paramlast[i] = val[vallist[i]];
                        totparam[i] = val[vallist[i]] + (totparam[i] == null ? 0 : Convert.ToDecimal(totparam[i].ToString()));//decimal.Parse(totparam[i].ToString()));
                    }
                    else if (i == cntminindex)
                    {
                        paramlast[i] = oldcols + "合计：";
                    }
                    else
                    {
                        try
                        {
                            paramlast[i] = DBNull.Value;
                        }
                        catch
                        {
                            paramlast[i] = 0;
                        }
                    }
                }
                if (!tminsumcol.Equals("null"))
                {
                    adrlast.ItemArray = paramlast;
                    dt.Rows.Add(adrlast);
                }

                adrlast = dt.NewRow();
                adrlast.ItemArray = totparam;
                dt.Rows.Add(adrlast);
            }
            catch (Exception)
            {
            }

            #endregion 合计列 对小计列进行合计

            return dt;
        }

        private string[] _colslilst;

        /// <summary>
        /// 自定义条件列名集合TEXT&VALUE
        /// </summary>
        public string[] Colslilst
        {
            get { return _colslilst; }
            set { _colslilst = value; }
        }

        private string _splitCol;
        /// <summary>
        /// 合计列

        /// </summary>
        public string SplitCol
        {
            get { return _splitCol; }
            set { _splitCol = value; }
        }

        private string _sumCol;

        /// <summary>
        /// 小计列 A,B&C&D
        /// </summary>
        public string SumCol
        {
            get { return _sumCol; }
            set { _sumCol = value; }
        }

        private int _totRowcount;

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotRowcount
        {
            get { return _totRowcount; }
            set { _totRowcount = value; }
        }

        private int _totPageCount;
        /// <summary>
        /// 总页数

        /// </summary>
        public int TotPageCount
        {
            get { return _totPageCount; }
            set { _totPageCount = value; }
        }

        private int _curPage;

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurPage
        {
            get { return _curPage; }
            set { _curPage = value; }
        }

        private string _colsliststr;
        /// <summary>
        /// 所有列字符串

        /// </summary>
        public string Colsliststr
        {
            get { return _colsliststr; }
            set { _colsliststr = value; }
        }

        private DataTable _curSplitDt;

        public DataTable CurSplitDt
        {
            get { return _curSplitDt; }
            set { _curSplitDt = value; }
        }

        private string _sumsetting;
        /// <summary>
        /// 小计列

        /// 使用小计功能注意排序
        /// {0},{1},{2}
        /// 小计,合计,求和：v1&v2&....
        /// 示例: 按YHBH小计,COMPANYID合计
        /// 传值：YHBH,COMPANYID,COL1&COL2&....
        /// </summary>
        public string Sumsetting
        {
            get { return _sumsetting; }
            set { _sumsetting = value; }
        }
    }
}